package com.customers.controller;

import com.customers.entity.Message;
import com.customers.entity.User;
import com.customers.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String newusername = request.getParameter("newusername");
        String newuserpass = request.getParameter("newpassword");

        User user = new User(null,newusername,newuserpass);
        Message message = null;
        try {
            UserService userService = (UserService)request.getServletContext().getAttribute("UserService");
            String registersql = "userRegister";
            String searchsql = "userLogin";
            message = userService.userRegister(user,searchsql,registersql);
//           message = UserServic.userRegister(user);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(message.getCode()==0){
           //注册失败，重新输入用户名或密码
            request.setAttribute("registerError",message);
            request.getRequestDispatcher("userregister.jsp").forward(request,response);
        }
        else{
            //注册成功
            request.setAttribute("newuser",message.getObject());
            request.getSession().setAttribute("registerSeccess",message.getObject());
            response.sendRedirect("Form.jsp");
        }
    }
}
